package com.etcn.modules.busi.order.service.impl;

import com.etcn.common.service.impl.CrudServiceImpl;
import com.etcn.common.utils.UserUtil;
import com.etcn.modules.busi.order.dao.IWmInvoiceDao;
import com.etcn.modules.busi.order.pojo.WmInvoice;
import com.etcn.modules.busi.order.pojo.WmOrder;
import com.etcn.modules.busi.order.service.IWmInvoiceService;
import com.etcn.modules.busi.order.service.IWmOrderService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 发票serviceImpl
 * 
 * @author guozc
 * @date 2018-03-20 13:18:02
 */
@Service("wmInvoiceService")
public class WmInvoiceServiceImpl extends CrudServiceImpl<IWmInvoiceDao, WmInvoice> implements IWmInvoiceService {

	@Autowired
	private IWmOrderService wmOrderService;

	@Override
	public void add(WmInvoice wmInvoice) throws Exception {
		String[] orderSns = wmInvoice.getOrderSns();
		if(orderSns != null){
			// 保存发票
			wmInvoice.setOrderSn(StringUtils.join(orderSns, ","));
			wmInvoice.setMemberId(UserUtil.getCurrentMemberId());
			wmInvoice.setApplyTime(new Date());
			wmInvoice.setStatus("1");
			float invoiceAmount = 0;
			for(String orderSn : orderSns){
				WmOrder order = wmOrderService.getByOrderSn(orderSn);
				invoiceAmount += Float.parseFloat(order.getOrderAmount());
				// 更新订单为已开票
				WmOrder entity = new WmOrder();
				entity.setOrderSn(orderSn);
				entity.setInvoiced("1");
				wmOrderService.updateByOrderSn(entity);
			}
			wmInvoice.setInvoiceAmount(String.valueOf(invoiceAmount));
			dao.insert(wmInvoice);
		}
	}

	@Override
	public List<WmInvoice> getMemberInvoices() throws Exception {
		WmInvoice entity = new WmInvoice();
		entity.setMemberId(UserUtil.getCurrentMemberId());
		return dao.findList(entity);
	}

}